package com.yuanqiao.insight.modules.download.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqiao.insight.modules.download.entity.UtlDownloadManage;
import com.yuanqiao.insight.modules.download.service.IUtlDownloadManageService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.system.query.QueryGenerator;
import com.insight.common.system.vo.LoginUser;
import com.insight.common.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.file.FileSystemException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/sys/downloadManage")
@Slf4j
public class UtlDownloadManageController {

    @Autowired
    private IUtlDownloadManageService sysDownloadManageService;  // 下载记录服务

    /**
     * 分页查询当前登录用户的下载记录
     *
     * @param utlDownloadManage  用于封装查询条件的实体类（支持自动构建 QueryWrapper）
     * @param pageNo            当前页码，默认第1页
     * @param pageSize          每页显示条数，默认10条
     * @param req               HTTP请求，用于获取请求参数
     * @return                  返回分页查询结果，包含下载记录列表
     */
    @AutoLog(value = "数据字典-查询字典配置")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<UtlDownloadManage>> queryPageList(UtlDownloadManage utlDownloadManage,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        Result<IPage<UtlDownloadManage>> result = new Result<>();

        // 根据传入实体和请求参数动态构建查询条件
        QueryWrapper<UtlDownloadManage> queryWrapper = QueryGenerator.initQueryWrapper(utlDownloadManage, req.getParameterMap());

        // 示例：如果需要根据时间区间查询，可以使用between，暂时注释掉
//        if (StringUtils.isNotEmpty(utlDownloadManage.getRequestTimeAfter()) && StringUtils.isNotEmpty(utlDownloadManage.getRequestTimeBefore())) {
//            queryWrapper.between("request_time",utlDownloadManage.getRequestTimeAfter(),utlDownloadManage.getRequestTimeBefore());
//        }

        // 按创建时间升序排序
        queryWrapper.orderByAsc("create_time");

        // 获取当前登录用户信息，从Security上下文获取
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 只查询当前登录用户创建的下载记录
        queryWrapper.eq("create_by", sysUser.getUsername());

        // 构造分页对象
        Page<UtlDownloadManage> page = new Page<>(pageNo, pageSize);
        // 执行分页查询
        IPage<UtlDownloadManage> pageList = sysDownloadManageService.page(page, queryWrapper);

        // 返回成功结果
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 根据ID删除下载记录及其对应的文件
     *
     * @param id 下载记录ID
     * @return   返回删除结果
     */
    @AutoLog(value = "多数据源管理-通过id删除")
    @ApiOperation(value = "多数据源管理-通过id删除", notes = "多数据源管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        // 查询对应的下载记录
        UtlDownloadManage utlDownloadManage = sysDownloadManageService.getById(id);

        // 删除对应的物理文件，路径和删除逻辑由CommonUtils.deleteFile实现
        boolean b = CommonUtils.deleteFile(Arrays.asList(utlDownloadManage.getFileName()));
        if (!b) {
            return Result.error("删除失败!");
        }

        // 删除数据库中的记录
        sysDownloadManageService.removeById(id);

        return Result.ok("删除成功!");
    }

    /**
     * 批量删除下载记录及对应文件
     *
     * @param ids 多个下载记录ID，逗号分隔
     * @return    返回批量删除结果
     */
    @AutoLog(value = "多数据源管理-批量删除")
    @ApiOperation(value = "多数据源管理-批量删除", notes = "多数据源管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids") String ids) throws FileSystemException {
        // 将传入的逗号分隔字符串转为集合
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            // 查询下载记录
            UtlDownloadManage utlDownloadManage = sysDownloadManageService.getById(id);
            // 物理删除文件，假设文件存储路径为 resource目录下
            File myObj = new File("resource\\" + utlDownloadManage.getFileName());
            boolean deleted = myObj.delete();
            if (!deleted) {
                log.warn("文件删除失败: " + myObj.getAbsolutePath());
                throw new FileSystemException("文件删除失败: " + myObj.getAbsolutePath());
            }
            // 删除数据库记录
            sysDownloadManageService.removeById(id);
        }
        return Result.ok("批量删除成功！");
    }
}
